package com.supreme.nettyapp.generalclient.beatclient.controller;

import com.supreme.nettyapp.generalclient.beatclient.service.BeatClientService;
import io.netty.handler.codec.mqtt.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Random;

@RestController
@RequestMapping(value = "beat")
public class BeatClientController {

    @Resource
    private BeatClientService beatClientService;

    @GetMapping(value = "ping")
    public String ping() {
        MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PINGREQ, false, MqttQoS.AT_MOST_ONCE, false, 0);
        MqttMessageIdVariableHeader messageIdVariableHeader = MqttMessageIdVariableHeader.from(new Random().nextInt(65536));
        MqttMessage mqttMessage = MqttMessageFactory.newMessage(fixedHeader, messageIdVariableHeader, null);
        beatClientService.writeAndFlush(mqttMessage);
        return "success";
    }
}
